#include "memberservice.h"
#include <QDateTime>
#include <QDebug>
#include <QRegularExpression>

MemberService::MemberService(Database *db) : m_db(db)
{
    m_memberDAO = new MemberDAO(db);
}

MemberService::~MemberService()
{
    delete m_memberDAO;
}

QMap<QString, QVariant> MemberService::getFormattedMemberInfo(int memberId)
{
    QMap<QString, QVariant> memberInfo = m_memberDAO->getCompleteeMemberInfo(memberId);
    
    if (memberInfo.isEmpty()) {
        return QMap<QString, QVariant>();
    }

    // 格式化数据用于界面显示
    QMap<QString, QVariant> formattedInfo;
    
    formattedInfo["customer_id"] = memberInfo["customer_id"];
    formattedInfo["name"] = memberInfo["name"];
    formattedInfo["phone"] = memberInfo["phone"];
    formattedInfo["level_id"] = memberInfo["level_id"];
    formattedInfo["level_name"] = formatMemberLevel(memberInfo["level_id"].toInt(), memberInfo["level_name"].toString());
    formattedInfo["discount_rate"] = QString::number(memberInfo["discount_rate"].toDouble() * 100, 'f', 0) + "%";
    formattedInfo["balance"] = formatAmount(memberInfo["balance"].toDouble());
    formattedInfo["total_recharged"] = formatAmount(memberInfo["total_recharged"].toDouble());
    formattedInfo["register_time"] = formatDateTime(memberInfo["register_time"]);
    formattedInfo["account_create_time"] = formatDateTime(memberInfo["account_create_time"]);
    formattedInfo["last_update"] = formatDateTime(memberInfo["last_update"]);

    return formattedInfo;
}

QVector<QMap<QString, QVariant>> MemberService::getAllMembersForDisplay()
{
    QVector<QMap<QString, QVariant>> members = m_memberDAO->getAllMembers();
    qDebug() << "DAO层返回会员数据，共" << members.size() << "条记录";
    if (!members.isEmpty()) {
        qDebug() << "DAO返回第一条记录:" << members.first();
    }
    
    QVector<QMap<QString, QVariant>> formattedMembers;

    for (const auto &member : members) {
        QMap<QString, QVariant> formattedMember;
        formattedMember["customer_id"] = member["customer_id"];
        formattedMember["name"] = member["name"];
        formattedMember["phone"] = member["phone"];
        formattedMember["level_name"] = formatMemberLevel(member["level_id"].toInt(), member["level_name"].toString());
        formattedMember["discount_rate"] = QString::number(member["discount_rate"].toDouble() * 100, 'f', 0) + "%";
        formattedMember["balance"] = formatAmount(member["balance"].toDouble());
        formattedMember["total_recharged"] = formatAmount(member["total_recharged"].toDouble());
        formattedMember["register_time"] = formatDateTime(member["register_time"]);
        
        qDebug() << "Service层格式化后的会员记录:" << formattedMember;
        formattedMembers.append(formattedMember);
    }
    
    qDebug() << "Service层返回格式化会员数据，共" << formattedMembers.size() << "条记录";

    return formattedMembers;
}

QVector<QMap<QString, QVariant>> MemberService::getMemberLevelHistory(int memberId)
{
    QVector<QMap<QString, QVariant>> history = m_memberDAO->getMemberLevelHistory(memberId);
    QVector<QMap<QString, QVariant>> formattedHistory;

    for (const auto &record : history) {
        QMap<QString, QVariant> formattedRecord;
        formattedRecord["history_id"] = record["history_id"];
        formattedRecord["customer_name"] = record["customer_name"];
        formattedRecord["old_level"] = formatMemberLevel(record["old_level_id"].toInt(), record["old_level_name"].toString());
        formattedRecord["new_level"] = formatMemberLevel(record["new_level_id"].toInt(), record["new_level_name"].toString());
        formattedRecord["change_reason"] = getChangeReasonText(record["change_reason"].toString());
        formattedRecord["change_time"] = formatDateTime(record["change_time"]);
        formattedRecord["note"] = record["note"];
        
        formattedHistory.append(formattedRecord);
    }

    return formattedHistory;
}

QString MemberService::formatMemberLevel(int levelId, const QString &levelName)
{
    if (levelName.isEmpty()) {
        return getLevelDisplayName(levelId);
    }
    return levelName;
}

QString MemberService::formatAmount(double amount)
{
    return QString("¥%1").arg(QString::number(amount, 'f', 2));
}

QString MemberService::formatDateTime(const QVariant &dateTime)
{
    if (dateTime.isNull() || !dateTime.isValid()) {
        return "未设置";
    }
    
    QDateTime dt = dateTime.toDateTime();
    if (!dt.isValid()) {
        return "无效日期";
    }
    
    return dt.toString("yyyy-MM-dd hh:mm:ss");
}

bool MemberService::isValidMemberId(int memberId)
{
    if (memberId <= 0) {
        return false;
    }
    
    QMap<QString, QVariant> memberInfo = m_memberDAO->getMemberById(memberId);
    return !memberInfo.isEmpty();
}

QString MemberService::getLevelDisplayName(int levelId)
{
    switch (levelId) {
        case 0: return "非会员";
        case 1: return "初级会员";
        case 2: return "中级会员";
        case 3: return "高级会员";
        default: return "未知等级";
    }
}

QString MemberService::getChangeReasonText(const QString &reason)
{
    if (reason == "1") return "充值升级";
    if (reason == "2") return "手动调整";
    if (reason == "3") return "其他";
    return reason;
}

bool MemberService::addMember(const QString &name, const QString &phone)
{
    // 输入验证
    if (name.trimmed().isEmpty()) {
        qDebug() << "会员姓名不能为空";
        return false;
    }
    
    if (phone.trimmed().isEmpty()) {
        qDebug() << "手机号码不能为空";
        return false;
    }
    
    // 手机号格式验证
    QRegularExpression phoneRegex("^1[3-9]\\d{9}$");
    if (!phoneRegex.match(phone.trimmed()).hasMatch()) {
        qDebug() << "手机号码格式不正确";
        return false;
    }
    
    // 调用DAO层添加会员
    bool result = m_memberDAO->addMember(name.trimmed(), phone.trimmed());
    
    if (result) {
        qDebug() << "会员添加成功:" << name << ", 手机号:" << phone;
    } else {
        qDebug() << "会员添加失败:" << name << ", 手机号:" << phone;
    }
    
    return result;
}

/**
 * 会员充值业务逻辑处理
 * 业务层级：业务逻辑层
 * 功能说明：处理会员充值的完整业务流程，包括参数验证、充值处理和结果格式化
 * 处理流程：
 * 1. 验证充值参数的有效性
 * 2. 调用DAO层执行充值操作
 * 3. 处理充值结果和异常情况
 * 
 * @param memberId 会员ID
 * @param amount 充值金额
 * @param remark 充值备注
 * @return 充值是否成功
 */
bool MemberService::processMemberRecharge(int memberId, double amount, const QString &remark)
{
    // 1. 验证充值参数
    if (!validateRechargeParams(memberId, amount)) {
        return false;
    }
    
    // 2. 调用DAO层执行充值
    bool result = m_memberDAO->processMemberRecharge(memberId, amount, remark);
    
    if (result) {
        qDebug() << "会员充值成功 - ID:" << memberId << ", 金额:" << amount << ", 备注:" << remark;
    } else {
        qDebug() << "会员充值失败 - ID:" << memberId << ", 金额:" << amount;
    }
    
    return result;
}

bool MemberService::validateRechargeParams(int memberId, double amount)
{
    // 验证会员ID
    if (memberId <= 0) {
        qDebug() << "无效的会员ID:" << memberId;
        return false;
    }
    
    // 验证会员是否存在
    if (!isValidMemberId(memberId)) {
        qDebug() << "会员不存在:" << memberId;
        return false;
    }
    
    // 验证充值金额
    if (amount <= 0) {
        qDebug() << "充值金额必须大于0:" << amount;
        return false;
    }
    
    if (amount > 99999.99) {
        qDebug() << "单次充值金额不能超过99999.99元:" << amount;
        return false;
    }
    
    return true;
}

QMap<QString, QVariant> MemberService::predictLevelAfterRecharge(int memberId, double amount)
{
    QMap<QString, QVariant> result;
    
    // 获取当前会员信息
    QMap<QString, QVariant> memberInfo = getFormattedMemberInfo(memberId);
    if (memberInfo.isEmpty()) {
        return result;
    }
    
    // 计算充值后的累计金额
    double currentTotal = memberInfo["total_recharged"].toDouble();
    double newTotal = currentTotal + amount;
    
    // 计算新等级
    int newLevelId = m_memberDAO->calculateMemberLevel(newTotal);
    QMap<QString, QVariant> newLevelInfo = m_memberDAO->getMemberLevelInfo(newLevelId);
    
    // 填充结果
    result["current_level_id"] = memberInfo["level_id"];
    result["current_level_name"] = memberInfo["level_name"];
    result["current_total"] = currentTotal;
    result["recharge_amount"] = amount;
    result["new_total"] = newTotal;
    result["new_level_id"] = newLevelId;
    result["new_level_name"] = newLevelInfo.value("level_name", "未知等级");
    result["level_changed"] = (newLevelId != memberInfo["level_id"].toInt());
    
    return result;
}

QString MemberService::formatRechargeResult(int memberId, double amount, bool levelChanged,
                                          const QString &oldLevel, const QString &newLevel)
{
    QString result;
    
    if (levelChanged) {
        result = QString("充值成功！充值金额：%1，会员等级从 %2 升级为 %3")
                .arg(formatAmount(amount))
                .arg(oldLevel)
                .arg(newLevel);
    } else {
        result = QString("充值成功！充值金额：%1，当前等级：%2")
                .arg(formatAmount(amount))
                .arg(oldLevel);
    }
    
    return result;
}
